/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.sgf.core.manager;

import com.inspur.edp.sgf.core.cache.ConfigCacheResult;
import com.inspur.edp.sgf.core.cache.EapiConfigCacheManager;
import com.inspur.edp.sgf.core.cache.GlobalConfigCacheResult;
import com.inspur.edp.sgf.utils.bsession.BackendSessionUtils;
import com.inspur.edp.sgf.utils.cache.ConfigCacheUtil;
import io.iec.edp.caf.boot.event.startup.StartupCompletedEvent;
import io.iec.edp.caf.commons.layeringcache.cache.Cache;
import io.iec.edp.caf.rpc.api.service.RpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 功能描述:
 *
 * @ClassName: EapiConfigManager
 * @Author: Fynn Qi
 * @Date: 2021/4/26 10:56
 * @Version: V1.0
 */
public class EapiConfigManager implements ApplicationListener<StartupCompletedEvent> {

    private final Logger logger = LoggerFactory.getLogger(EapiConfigManager.class);

    private final RpcClient rpcClient;

    private final EapiConfigCacheManager eapiConfigCacheManager;

    public EapiConfigManager(RpcClient rpcClient, EapiConfigCacheManager eapiConfigCacheManager) {
        this.rpcClient = rpcClient;
        this.eapiConfigCacheManager = eapiConfigCacheManager;
    }

    public GlobalConfigCacheResult getEapiGlobalConfig() {
        //缓存不为空，从缓存中区
        if (eapiConfigCacheManager.getEapiConfigCache() != null) {
            GlobalConfigCacheResult cacheResult = eapiConfigCacheManager.getGlobalCacheResult();
            if (cacheResult != null) {
                return cacheResult;
            } else {
                return invokeGlobalConfigRpcService();
            }
        } else {
            return invokeGlobalConfigRpcService();
        }
    }

    private GlobalConfigCacheResult invokeGlobalConfigRpcService() {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        return rpcClient.invoke(GlobalConfigCacheResult.class, "com.inspur.edp.sgf.config.service.EapiConfigRpcService.getGlobalConfigs", "sg", map, new HashMap<>());
    }

    public ConfigCacheResult getEapiConfigs(String uri, String httpMethod) {
        Cache cache = eapiConfigCacheManager.getEapiConfigCache();
        //缓存不为空，从缓存中区
        if (cache != null) {
            String key = ConfigCacheUtil.getCacheKey(httpMethod, uri);
            ConfigCacheResult cacheResult = cache.get(key, ConfigCacheResult.class);
            //ConfigCacheResult不为空，则从缓存中取，为空则重新调用RPC获取
            if (cacheResult != null) {
                return cacheResult;
            } else {
                //todo 当前su未更新缓存
                return invokeEapiConfigsRpcService(uri, httpMethod);
            }
        } else {
            return invokeEapiConfigsRpcService(uri, httpMethod);
        }
    }

    private ConfigCacheResult invokeEapiConfigsRpcService(String uri, String httpMethod) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("uri", uri);
        map.put("httpMethod", httpMethod);
        return rpcClient.invoke(ConfigCacheResult.class, "com.inspur.edp.sgf.config.service.EapiConfigRpcService.getConfigs", "sg", map, new HashMap<>());
    }

    @Override
    public void onApplicationEvent(StartupCompletedEvent event) {
        try {
            BackendSessionUtils.wrapFirstTenantBackendSession(tenant -> {
                //todo 仅对第一个租户的缓存做了处理，后续改进
                eapiConfigCacheManager.clear();
                getEapiGlobalConfig();
            });
        } catch (Exception e) {
            logger.warn("初始化API权限配置全局缓存出错：" + e.getMessage(), e);
            eapiConfigCacheManager.removeGlobalCache();
        }
    }
}
